import React, { Component ,useState} from 'react'
import '../assets/style/btn.css'
export default function home()  {
  const [list ,setList]=useState([{name:'香蕉',price:30,num:2,id:1,select:true},
  {name:'苹果',price:50,num:2,id:2,select:true},{name:'梨',price:25,num:2,id:3,select:true},])
  // const [allSelect ,setAllSelect]=useState(true)

 const addNum = (e) => {
   list.forEach(item=>{
        if(item.id==e ){
             item.num++
        }
    })
    setList([...list])
    // this.setState({
    //     list: this.state.list
    //  })
}
const jianNum = (e) => {
   let a=false
  list.forEach(item=>{
        if(item.id==e && item.num>0){
             item.num--
             a=true
        }
    })
if(a){
  setList([...list])
 }      
}
const  checked=(e)=>{
   list[e].select=! list[e].select
   setList([...list])
   
}
const delGoods = (e) => {
    console.log(e);
    // this.setState({
    //    list: this.state.list.filter(item=>{return item.id != e})
    // })
    setList(list.filter(item=>{return item.id != e}))
}
const totals=React.useMemo(()=>{
  let t=0
    list.forEach(item=>{
        if(item.select){
             t+=item.price*item.num
        }
    })
    return t
},[list])



const allChecked=()=>{
  //  allSelect =  !allSelect
  //   list.forEach(item=>{
  //      item.select=this.state.allSelect
  //   })
  // setAllSelect(allSelect)
}

    return (
      <div>
       <div> 
            <div className='fa' >
            <div className='son'><input  onChange={ allChecked} type="checkbox" /></div>
                    <div className='son'>名称</div>
                    <div className='son'>单价</div>
                    <div className='son'>数量</div>
                    <div className='son'>总价</div>
                    <div className='son'>操作</div>
                  </div>   
                 {list.map((item,index)=> <div className='fa' key={item.name}>
                 <div className='son'><input type="checkbox" onChange={ ()=>checked(index)} checked={item.select} /></div>
                    <div className='son'>{item.name}</div>
                    <div className='son'>{item.price}</div>
                    <div className='cz' >
                        <div style={{marginLeft:'20px'}} className='jj'  onClick={ ()=>jianNum(item.id)}>-</div>{item.num}
                        <div className='jj' onClick={ ()=>addNum(item.id)}  >+</div>
                    </div> 
                    <div className='son'>{item.num*item.price}</div>
                    <div className='son' onClick={()=>{delGoods(item.id)}} >删除</div>
                 </div>)}
                <div>总价：{totals}</div>
            </div>
       
      </div>
    )
  }

